<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BMC实验管理平台 - 实验模板管理</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- Element Plus -->
    <script src="https://unpkg.com/element-plus"></script>
    <!-- Axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
        }
        #app {
            height: 100vh;
        }
        .header {
            background-color: #409EFF;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .main-container {
            padding: 20px;
        }
        .template-list {
            margin-top: 20px;
        }
        .yaml-editor {
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="header">
            <h1>BMC实验管理平台 - 实验模板管理</h1>
        </div>
        <div class="main-container">
            <!-- 顶部操作栏 -->
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-button type="primary" @click="showCreateDialog">创建模板</el-button>
                </el-col>
                <el-col :span="18">
                    <el-input
                        v-model="searchName"
                        placeholder="搜索模板名称"
                        clearable
                        @clear="fetchTemplates"
                        @keyup.enter="fetchTemplates"
                    >
                        <template #append>
                            <el-button icon="Search" @click="fetchTemplates"></el-button>
                        </template>
                    </el-input>
                </el-col>
            </el-row>

            <!-- 模板列表 -->
            <div class="template-list">
                <el-table
                    :data="templates"
                    v-loading="loading"
                    stripe
                    style="width: 100%"
                >
                    <el-table-column prop="id" label="ID" width="80"></el-table-column>
                    <el-table-column prop="name" label="模板名称" width="200"></el-table-column>
                    <el-table-column prop="description" label="描述"></el-table-column>
                    <el-table-column prop="tags" label="标签" width="200">
                        <template #default="scope">
                            <el-tag
                                v-for="tag in scope.row.tags"
                                :key="tag"
                                size="small"
                                style="margin-right: 5px"
                            >
                                {{ tag }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="version" label="版本" width="80"></el-table-column>
                    <el-table-column prop="created_at" label="创建时间" width="180">
                        <template #default="scope">
                            {{ formatDate(scope.row.created_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="300">
                        <template #default="scope">
                            <el-button size="small" @click="viewDetail(scope.row.id)">详情</el-button>
                            <el-button size="small" @click="editTemplate(scope.row.id)">编辑</el-button>
                            <el-button size="small" type="danger" @click="deleteTemplate(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="fetchTemplates"
                    @current-change="fetchTemplates"
                    style="margin-top: 20px; justify-content: center"
                />
            </div>
        </div>

        <!-- 创建/编辑模板对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="60%"
        >
            <el-form :model="form" label-width="100px">
                <el-form-item label="模板名称">
                    <el-input v-model="form.name" :disabled="isEditMode"></el-input>
                </el-form-item>
                <el-form-item label="模板描述">
                    <el-input v-model="form.description" type="textarea" rows="2"></el-input>
                </el-form-item>
                <el-form-item label="标签">
                    <el-select v-model="form.tags" multiple filterable allow-create placeholder="输入标签后回车添加">
                        <el-option
                            v-for="tag in existingTags"
                            :key="tag"
                            :label="tag"
                            :value="tag"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="YAML内容">
                    <el-input
                        v-model="form.yaml_content"
                        type="textarea"
                        rows="15"
                        class="yaml-editor"
                        placeholder="请输入YAML格式的模板内容"
                    ></el-input>
                </el-form-item>
                <el-form-item label="修改说明" v-if="isEditMode">
                    <el-input v-model="form.change_log" type="textarea" rows="2"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 模板详情对话框 -->
        <el-dialog
            v-model="detailDialogVisible"
            title="模板详情"
            width="70%"
        >
            <el-descriptions :column="2" border v-if="currentTemplate">
                <el-descriptions-item label="ID">{{ currentTemplate.id }}</el-descriptions-item>
                <el-descriptions-item label="名称">{{ currentTemplate.name }}</el-descriptions-item>
                <el-descriptions-item label="描述" :span="2">{{ currentTemplate.description }}</el-descriptions-item>
                <el-descriptions-item label="标签" :span="2">
                    <el-tag v-for="tag in currentTemplate.tags" :key="tag" size="small" style="margin-right: 5px">{{ tag }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="版本">{{ currentTemplate.version }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDate(currentTemplate.created_at) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间" :span="2">{{ formatDate(currentTemplate.updated_at) }}</el-descriptions-item>
            </el-descriptions>

            <el-divider>YAML内容</el-divider>
            <el-input
                v-model="currentTemplate.yaml_content"
                type="textarea"
                rows="15"
                readonly
                class="yaml-editor"
            />

            <el-divider>版本历史</el-divider>
            <el-timeline>
                <el-timeline-item
                    v-for="version in currentTemplate.version_history"
                    :key="version.version"
                    :timestamp="formatDate(version.created_at)"
                >
                    <h4>版本 {{ version.version }}</h4>
                    <p>{{ version.change_log }}</p>
                    <el-button size="small" @click="rollbackVersion(currentTemplate.id, version.version)" v-if="version.version !== currentTemplate.version">
                        回滚到此版本
                    </el-button>
                </el-timeline-item>
            </el-timeline>
        </el-dialog>
    </div>

    <script>
        const { createApp } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        const API_BASE = 'http://localhost:8000';

        createApp({
            data() {
                return {
                    templates: [],
                    loading: false,
                    currentPage: 1,
                    pageSize: 20,
                    total: 0,
                    searchName: '',
                    dialogVisible: false,
                    detailDialogVisible: false,
                    isEditMode: false,
                    currentTemplate: null,
                    currentTemplateId: null,
                    existingTags: ['test', 'demo', 'production'],
                    form: {
                        name: '',
                        description: '',
                        yaml_content: '',
                        tags: [],
                        change_log: ''
                    }
                };
            },
            computed: {
                dialogTitle() {
                    return this.isEditMode ? '编辑模板' : '创建模板';
                }
            },
            mounted() {
                this.fetchTemplates();
            },
            methods: {
                async fetchTemplates() {
                    this.loading = true;
                    try {
                        const response = await axios.get(`${API_BASE}/api/experiment-templates`, {
                            params: {
                                page: this.currentPage,
                                page_size: this.pageSize,
                                name: this.searchName || undefined
                            }
                        });
                        this.templates = response.data.items;
                        this.total = response.data.total;
                    } catch (error) {
                        ElMessage.error('获取模板列表失败: ' + (error.response?.data?.detail || error.message));
                    } finally {
                        this.loading = false;
                    }
                },
                showCreateDialog() {
                    this.isEditMode = false;
                    this.form = {
                        name: '',
                        description: '',
                        yaml_content: '',
                        tags: [],
                        change_log: ''
                    };
                    this.dialogVisible = true;
                },
                async editTemplate(id) {
                    try {
                        const response = await axios.get(`${API_BASE}/api/experiment-templates/${id}`);
                        this.isEditMode = true;
                        this.currentTemplateId = id;
                        this.form = {
                            name: response.data.name,
                            description: response.data.description,
                            yaml_content: response.data.yaml_content,
                            tags: response.data.tags || [],
                            change_log: ''
                        };
                        this.dialogVisible = true;
                    } catch (error) {
                        ElMessage.error('获取模板详情失败: ' + (error.response?.data?.detail || error.message));
                    }
                },
                async viewDetail(id) {
                    try {
                        const response = await axios.get(`${API_BASE}/api/experiment-templates/${id}`);
                        this.currentTemplate = response.data;
                        this.detailDialogVisible = true;
                    } catch (error) {
                        ElMessage.error('获取模板详情失败: ' + (error.response?.data?.detail || error.message));
                    }
                },
                async submitForm() {
                    if (!this.form.name || !this.form.yaml_content) {
                        ElMessage.warning('请填写模板名称和YAML内容');
                        return;
                    }

                    try {
                        if (this.isEditMode) {
                            await axios.put(`${API_BASE}/api/experiment-templates/${this.currentTemplateId}`, {
                                yaml_content: this.form.yaml_content,
                                description: this.form.description,
                                tags: this.form.tags,
                                change_log: this.form.change_log
                            });
                            ElMessage.success('模板更新成功');
                        } else {
                            await axios.post(`${API_BASE}/api/experiment-templates`, {
                                name: this.form.name,
                                description: this.form.description,
                                yaml_content: this.form.yaml_content,
                                tags: this.form.tags,
                                created_by: 'web_user'
                            });
                            ElMessage.success('模板创建成功');
                        }
                        this.dialogVisible = false;
                        this.fetchTemplates();
                    } catch (error) {
                        ElMessage.error('操作失败: ' + (error.response?.data?.detail || error.message));
                    }
                },
                async deleteTemplate(id) {
                    try {
                        await ElMessageBox.confirm('确定要删除这个模板吗？', '警告', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        });

                        await axios.delete(`${API_BASE}/api/experiment-templates/${id}`);
                        ElMessage.success('模板已删除');
                        this.fetchTemplates();
                    } catch (error) {
                        if (error !== 'cancel') {
                            ElMessage.error('删除失败: ' + (error.response?.data?.detail || error.message));
                        }
                    }
                },
                async rollbackVersion(id, version) {
                    try {
                        await ElMessageBox.confirm(`确定要回滚到版本 ${version} 吗？`, '确认', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        });

                        await axios.post(`${API_BASE}/api/experiment-templates/${id}/versions/${version}/rollback`);
                        ElMessage.success(`已回滚到版本 ${version}`);
                        this.detailDialogVisible = false;
                        this.fetchTemplates();
                    } catch (error) {
                        if (error !== 'cancel') {
                            ElMessage.error('回滚失败: ' + (error.response?.data?.detail || error.message));
                        }
                    }
                },
                formatDate(dateString) {
                    if (!dateString) return '';
                    const date = new Date(dateString);
                    return date.toLocaleString('zh-CN');
                }
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>
